package com.ftg.learn.assess.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.assess.client.UploadClient;
import com.ftg.learn.assess.dto.AdminUpdateAssessDto;
import com.ftg.learn.assess.dto.AdminPageQueryDto;
import com.ftg.learn.assess.entity.Assess;
import com.ftg.learn.assess.mappper.AssessMapper;
import com.ftg.learn.assess.result.PageResult;
import com.ftg.learn.assess.result.Result;
import com.ftg.learn.assess.service.AssessService;
import com.ftg.learn.assess.service.MediaService;
import com.ftg.learn.assess.vo.UserGetAllAssessByEvaluationIdVo;
import com.ftg.learn.assess.vo.UserGetMeAssessVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;


@Service
@RequiredArgsConstructor
@Slf4j
public class AssessServiceImpl extends ServiceImpl<AssessMapper, Assess> implements AssessService {
    @Autowired
    private final UploadClient uploadClient;
    @Autowired
    private MediaService mediaService;
    @Autowired
    private RedisTemplate redisTemplate;
    private static final String COURSE_KEY = "hiit:assess:unit:";
    private static final String MEDIA_KEY = "hiit:assess:info:";

    @Override
    public Result<List<UserGetAllAssessByEvaluationIdVo>> getProductAssessByEvaluationId(Long productId) {
        String key = COURSE_KEY + productId;
        List<Assess> assessList = redisTemplate.opsForList().range(key, 0, -1);
        if(assessList.size()>0){
            log.info("从redis中获取数据{}",assessList);
            List<UserGetAllAssessByEvaluationIdVo> userGetAllAssessByEvaluationIdVoList = BeanUtil.copyToList(assessList, UserGetAllAssessByEvaluationIdVo.class);
            return Result.build(200, "查询成功", userGetAllAssessByEvaluationIdVoList);
        }
        LambdaQueryWrapper<Assess> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery
                .eq(Assess::getProductId, productId)
                .eq(Assess::getStatus, 1);
       assessList = this.baseMapper.selectList(lambdaQuery);
        List<UserGetAllAssessByEvaluationIdVo> userGetAllAssessByEvaluationIdVoList = BeanUtil.copyToList(assessList, UserGetAllAssessByEvaluationIdVo.class);
        if(userGetAllAssessByEvaluationIdVoList.size() ==0){
            return Result.build(200, "没有评价");
        }
        redisTemplate.opsForList().rightPushAll(key, userGetAllAssessByEvaluationIdVoList);
        return Result.build(200, "查询成功", userGetAllAssessByEvaluationIdVoList);
    }
    @Override
    public Result<PageResult> pageQuery(AdminPageQueryDto queryDto) {
        Page<Assess> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());

        LambdaQueryWrapper<Assess> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery
                .like(StringUtils.hasText(queryDto.getContent()), Assess::getContent, queryDto.getContent())
                .eq(queryDto.getRating() != null, Assess::getRating, queryDto.getRating())
                .eq(queryDto.getIsAnonymous() != null, Assess::getIsAnonymous, queryDto.getIsAnonymous())
                .eq(queryDto.getStatus() != null, Assess::getStatus, queryDto.getStatus())
                .eq(queryDto.getProductId() != null, Assess::getProductId, queryDto.getProductId());
        Page<Assess> sysUserEntityPage = this.baseMapper.selectPage(page, lambdaQuery);
        if(sysUserEntityPage.getTotal() == 0){
            return Result.build(200, "分页查询成功，无数据", new PageResult(0, null));
        }
        return Result.build(200, "分页查询成功", new PageResult(sysUserEntityPage.getTotal(), sysUserEntityPage.getRecords()));
    }

    @Override
    public Result<String> updateProductAssess(AdminUpdateAssessDto updateAssessDto) {
        LambdaUpdateWrapper<Assess> lambdaUpdate = Wrappers.lambdaUpdate();
        lambdaUpdate
                .eq(Assess::getEvaluationId, updateAssessDto.getEvaluationId())
                .set(Assess::getStatus, updateAssessDto.getStatus())
                .set(Assess::getHideReason, updateAssessDto.getHideReason());
        int update = this.baseMapper.update(null, lambdaUpdate);
        return update > 0 ? Result.build(200, "更新成功") : Result.build(500, "更新失败");
    }

    @Override
    @Transactional
    public Result<String> removeProductAssess(Long evaluationId) {
        int delete = this.baseMapper.delete(Wrappers.lambdaQuery(Assess.class).eq(Assess::getEvaluationId, evaluationId));
        mediaService.removeAssessMedia(evaluationId);
        return delete > 0 ? Result.build(200, "删除成功") : Result.build(500, "删除失败");
    }

    @Override
    public Result<List<UserGetMeAssessVo>> getMeAssess(Long userId) {
        LambdaQueryWrapper<Assess> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery
                .eq(Assess::getUserId, userId)
                .eq(Assess::getStatus, 1)
                .orderByDesc(Assess::getCreateTime)
        ;
        List<Assess> list = this.baseMapper.selectList(lambdaQuery);
        List<UserGetMeAssessVo> userGetMeAssessVos = BeanUtil.copyToList(list, UserGetMeAssessVo.class);
        if(userGetMeAssessVos.size()==0){
            return Result.build(500, "获取失败");
        }
        return Result.build(200, "获取成功", userGetMeAssessVos);
    }

    @Override
    @Transactional
    public Result<String> removeAssessByUserId(Long userId, Long evaluationId) {
        //根据用户id删除评价
        LambdaQueryWrapper<Assess> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Assess::getUserId, userId)
                .eq(Assess::getEvaluationId,  evaluationId);
        int result=this.baseMapper.delete(queryWrapper);
        mediaService.removeAssessMedia(evaluationId);
        if(result!=1){
            return Result.build(500, "删除失败");
        }
        redisTemplate.delete(COURSE_KEY+evaluationId);
        return Result.build(200, "删除成功");
    }

}
